package com.jhy.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jhy.core.domain.LoginUser;
import com.jhy.core.enums.DeviceType;
import com.jhy.core.helper.LoginHelper;
import com.jhy.core.utils.Check;
import com.jhy.exception.BaseException;
import com.jhy.system.domain.SysUser;
import com.jhy.system.domain.bo.SysUserLoginBo;
import com.jhy.system.mapper.SysUserMapper;
import com.jhy.system.mapper.TUserMapper;
import com.jhy.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements ISysUserService {

    private final SysUserMapper userMapper;

    @Override
    public Map<String, Object> login(SysUserLoginBo bo) {
        HashMap<String, Object> reqMap = new HashMap<>();
        SysUser sysUser =  doGetUserInfo(bo);

        if (sysUser == null) {
            throw new BaseException("用户名或密码错误");
        }
        if (!BCrypt.checkpw(bo.getPassword(), sysUser.getPassword())) {
            throw new BaseException("用户名或密码错误");
        }
        LoginUser loginUser = buildLoginUser(sysUser);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);
        reqMap.put("token", StpUtil.getTokenValue());
        reqMap.put("info", sysUser);
        return reqMap;
    }



    @Override
    public Boolean register(SysUserLoginBo bo) {
        SysUser sysUser =  doGetUserInfo(bo);
        if (Check.isNoEmpty(sysUser)){
            throw new BaseException("该用户已存在");
        }
        sysUser = new SysUser();
        sysUser.setUserName(bo.getUserName());
        sysUser.setNickName(bo.getUserName());
        sysUser.setPassword(BCrypt.hashpw(bo.getPassword()));
        userMapper.insert(sysUser);
        return true;
    }

    private SysUser doGetUserInfo(SysUserLoginBo bo) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, bo.getUserName());
        return userMapper.selectOne(wrapper);
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(SysUser user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUserName());
        loginUser.setNickName(user.getNickName());
        loginUser.setUserType(user.getUserType());
        return loginUser;
    }
}
